<template>
    <div style="display: flex; gap: 10px; height: 100%; min-height: 0; max-height: 100vh;" class="ws-chat-container">
        <!-- 新版聊天界面 -->
        <WsChatNew v-if="showNewVersion" :opponentId="opponentId" @switch-version="toggleVersion" />
        <!-- 旧版聊天界面 -->
        <template v-else>
        <!-- 左侧表单区域 -->
        <div style="flex: 1; min-width: 25%; max-width: 50%;">
            <!-- 添加key确保options更新时组件重新渲染 -->
            <!-- 修复elForm未定义的问题，添加el-form包裹 -->
            <el-form :model="wsForm" :rules="wsRules" ref="wsForm" label-position="top">
                <el-form-item prop="content">
                    <div id="editor"></div>
                </el-form-item>
                <div style="display: flex; gap: 10px; justify-content: center;">
                    <el-form-item prop="wsOppo">
                        <el-select 
                            v-model="wsForm.wsOppo" 
                            :disabled="userOptionsLoading" 
                            filterable 
                            placeholder="会话人" 
                            :key="userOptions.length"
                            :popper-append-to-body="true"
                            popper-class="ws-chat-select-dropdown">
                            <template v-if="userOptionsLoading">
                                <el-option label="加载中..." value="loading"></el-option>
                            </template>
                            <el-option v-for="item in userOptions" :key="item.value" :label="item.label" :value="item.value">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-button type="primary" plain @click="sendChatMsg">立即发送</el-button>
                    <el-button type="danger" plain @click="cleanChatMsg">清空记录</el-button>
                    <el-button plain size="small" @click="toggleAdvancedSettings" style="margin-right: 10px;">
                        {{ showAdvancedSettings ? '隐藏设置' : '高级设置' }}
                    </el-button>
                    <div v-show="showAdvancedSettings" style="margin-right: 10px;">
                        <el-radio-group v-model="messageType" size="small">
                            <el-radio label="chat">chat方式</el-radio>
                            <el-radio label="system">system方式</el-radio>
                        </el-radio-group>
                    </div>
                    <el-button type="success" plain @click="toggleVersion">{{ showNewVersion ? '返回旧版' : '切换到新版' }}</el-button>
                </div>
            </el-form>
        </div>

        <!-- 右侧消息容器 -->
        <div style="flex: 1; min-width: 50%; display: flex; flex-direction: column;">
            <!-- 添加ref属性以便滚动操作，同时隐藏滚动条 -->
            <div ref="messageContainer" style="flex: 1; overflow-y: auto; border: 1px solid #e4e7ed; padding: 10px; scrollbar-width: none; -ms-overflow-style: none; background-color: #f5f7fa; scroll-behavior: smooth; min-height: 300px; max-height: calc(100vh - 200px);">
                <div v-for="(msg, index) in msgList" :key="index" style="margin: 5px 0">
                    <div :style="{
                textAlign: msg.type === 'me' ? 'right' : msg.type === 'oppo' ? 'left' : 'center',
                marginBottom: '10px'
              }" @mouseenter="handleMouseEnter(index)" @mouseleave="handleMouseLeave(index)" @click="msg.type === 'oppo' ? markAsRead(index) : () => {}">
                        <div :style="{
                display: 'inline-block',
                padding: '4px 8px',
                borderRadius: '12px',
                backgroundColor: msg.type === 'me' ? '#e6f7ff' : msg.type === 'oppo' ? '#f0f9eb' : '#fff2f0',
                border: '1px solid',
                borderColor: msg.type === 'me' ? '#bae7ff' : msg.type === 'oppo' ? '#c2e9b0' : '#ffccc7',
                maxWidth: '80%',
                wordBreak: 'break-word',
                textAlign: 'left'
              }">
                            <!-- 消息状态标记 -->
            <span :style="{
                  display: 'inline-block',
                  width: '8px',
                  height: '8px',
                  backgroundColor: msg.isRead === 3 ? '#67c23a' /* 绿色 - 已读 */ : 
                                  msg.isRead === 2 ? '#f56c6c' /* 红色 - 未读 */ : 
                                  '#909399' /* 灰色 - 其他状态 */,
                  borderRadius: '50%',
                  marginRight: '4px'
                }"></span>
                            <span v-show="showTime[index]" :style="{ color: msg.type === 'me' ? '#409eff' : msg.type === 'oppo' ? '#67c23a' : '#f56c6c' }">
                                [{{ msg.time }}] {{ msg.type === 'me' ? '我' : msg.type === 'oppo' ? '对方' : '系统' }}:
                            </span>
                            <!-- <span v-html="msg.content"></span> -->
                            <el-card class="w-e-text" style="margin: 10px 0;">
                                <div v-html="msg.content"></div>
                            </el-card>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </template>
    </div>
</template>

<script>
import E from 'wangeditor'
import hljs from 'highlight.js'
import WsChatNew from './WsChatNew.vue'
export default {
    components: {
        WsChatNew
    },
    name: 'WsChat',
    props: {
        opponentId: {
            type: String,
            required: false,
            default: '',
        },
    },
    inject: {
        getWebsocket: {
            default: () => () => null,
        },
    }, // 获取父组件提供的websocket获取函数
    data() {
        return {
            userOptions: [],
            userOptionsLoading: false,
            msgList: [], //消息列表：发送或接收记录
            user: JSON.parse(localStorage.getItem('userInfo') || '{}'),
            wsForm: {
                // 站内信表单数据
                wsOppo: '',
                content: '',
            },
            wsRules: {
                // 站内信表单规则
                wsOppo: [
                    {
                        required: true,
                        message: '请选择会话人',
                        trigger: 'change',
                    },
                ],
                content: [
                    {
                        required: true,
                        message: '消息内容不能为空',
                        trigger: 'blur',
                    },
                ],
            },
            showTime: {}, // 使用对象存储每个消息的时间显示状态
            timers: {}, // 使用对象存储每个消息的定时器
            messageType: 'chat', // 消息发送方式：chat或system，默认为chat
            showAdvancedSettings: false, // 是否显示高级设置
            showNewVersion: false // 是否显示新版聊天界面
        }
    },
    mounted() {
        // 页面加载时，先初始化用户选项，再初始化其他组件
        this.init()
        this.initUsersOptions()
    },
    computed: {},
    watch: {
        msgList: {
            handler(){
                this.$nextTick(() => {
                    this.scrollToBottom()
                })
            }
        },
        // 监听路由参数变化
        '$route.query.opponentId': {
            handler(newVal) {
                if (newVal && this.userOptions.length > 0) {
                    this.autoSelectOpponent()
                }
            },
            immediate: true
        },
        // 监听props变化
        opponentId: {
            handler(newVal) {
                if (newVal && this.userOptions.length > 0) {
                    this.autoSelectOpponent()
                }
            },
            immediate: true
        },
        // 监听用户选项加载完成
        userOptions: {
            handler(newOptions) {
                if (newOptions && newOptions.length > 0) {
                    this.autoSelectOpponent()
                }
            },
            deep: true
        },
        // 监听会话人变化，清空聊天记录
        'wsForm.wsOppo'(newVal, oldVal) {
            if (newVal !== oldVal) {
                // 清空旧记录
                this.msgList = []
                if (newVal && this.user) {
                    // 添加this.user存在性检查
                    // 调用抽离后的方法获取聊天记录
                    this.fetchChatRecords(this.user.id, newVal)
                }
            }
        },
        // 监听高级设置显示状态变化，处理焦点和aria-hidden冲突
        showAdvancedSettings(newVal) {
            if (!newVal) {
                // 当隐藏高级设置时，主动移除单选框的焦点
                this.$nextTick(() => {
                    const focusedElement = document.activeElement
                    if (focusedElement && 
                        (focusedElement.classList.contains('el-radio__original') || 
                         focusedElement.closest('.el-radio-group'))) {
                        focusedElement.blur()
                    }
                })
            }
        }
    },
    methods: {
        // 切换版本
        toggleVersion() {
            this.showNewVersion = !this.showNewVersion;
            // 当从新版切回旧版时，如果编辑器未初始化，则重新初始化
            if (!this.showNewVersion && !this.editor) {
                this.$nextTick(() => {
                    this.initializeEditor();
                });
            }
            // 自动调整弹窗大小以适应内容
            this.$nextTick(() => {
                this.adjustModalSize();
            });
        },
        // 调整弹窗大小以适应内容
        adjustModalSize() {
            // 尝试获取当前弹窗容器
            const modalContainer = document.querySelector('.el-dialog__wrapper') || document.querySelector('.modal-container');
            if (modalContainer) {
                // 设置最大高度为视窗高度的90%
                const maxHeight = window.innerHeight * 0.9;
                const maxWidth = window.innerWidth * 0.95;
                
                // 应用样式到弹窗容器
                modalContainer.style.maxHeight = `${maxHeight}px`;
                modalContainer.style.maxWidth = `${maxWidth}px`;
                modalContainer.style.overflow = 'hidden'; // 避免弹窗出现滚动条
                modalContainer.style.margin = 'auto';
                
                // 获取聊天容器
                const chatContainer = modalContainer.querySelector('.ws-chat-container');
                if (chatContainer) {
                    // 确保聊天容器不会超出弹窗
                    chatContainer.style.maxHeight = `${maxHeight - 20}px`; // 减去一些边距
                    chatContainer.style.height = 'auto';
                    chatContainer.style.width = '100%';
                    chatContainer.style.boxSizing = 'border-box';
                }
                
                console.log('WsChat弹窗大小已自动调整');
            }
            // 添加窗口大小变化监听
            window.addEventListener('resize', this.handleResize);
        },
        // 处理窗口大小变化
        handleResize() {
            if (this.showNewVersion) {
                this.adjustModalSize();
            }
        },
        // 移除窗口大小变化监听
        removeResizeListener() {
            window.removeEventListener('resize', this.handleResize);
        },
        // 抽离的获取聊天记录方法
        fetchChatRecords(userId, oppoId) {
            this.wsLoading = true
            this.$request
                .get('/chat/getChatRecords', {
                    params: {
                        userId: userId,
                        oppoId: oppoId,
                    },
                })
                .then((res) => {
                    if (res.code === '200') {
                        this.msgList = res.data.map((item) => ({
                            id: item.id, // 消息ID
                            type:
                                item.userId === this.user.id.toString()
                                    ? 'me'
                                    : 'oppo',
                            content: item.content,
                            time: item.creatTime, // 假设需要格式化时间
                            isRead: item.isRead
                        }))
                    } else {
                        this.$message.error('获取聊天记录失败：' + res.msg)
                    }
                })
                .catch((error) => {
                    this.$message.error('网络错误，获取聊天记录失败')
                })
                .finally(() => {
                    this.wsLoading = false
                })
        },
        handleMouseEnter(index) {
            // 为每个消息项设置独立的定时器
            this.clearTimer(index)
            this.timers[index] = setTimeout(() => {
                this.$set(this.showTime, index, true)
            }, 3000)
        },
        handleMouseLeave(index) {
            this.clearTimer(index)
            this.$set(this.showTime, index, false)
        },
        // 标记消息为已读
        markAsRead(index) {
            if (
                this.msgList[index].type === 'oppo' &&
                this.msgList[index].isRead === 2
            ) {
                this.$set(this.msgList[index], 'isRead', 3)
                // 发送已读状态到服务器
                this.sendReadStatusToServer(this.msgList[index])
            }
        },
        // 处理对方已读消息的通知
        handleReadAck(msg) {
            if (msg.oppo === this.user.id && msg.uid === this.wsForm.wsOppo) {
                // 找到对应的消息并更新状态
                const index = this.msgList.findIndex(
                    (item) => item.id === msg.msgId && item.type === 'me'
                )
                if (index !== -1) {
                    this.$set(this.msgList[index], 'isRead', 3)
                }
            }
        },
        // 处理刷新通知
        handleRefresh(msg) {
            //将消息列表的某条消息状态修改为已读
            const index = this.msgList.findIndex(
                (item) => item.id === msg.id && item.type === 'me'
            )
            if (index !== -1) {
                this.$set(this.msgList[index], 'isRead', 3)
            }
        },
        // 发送已读状态到服务器和对方
        sendReadStatusToServer(msg) {
            // 实现发送已读状态到服务器的逻辑
            if (msg && msg.id) {
                // 1. 调用API更新服务器状态
                this.$request
                    .post('/chat/markAsRead', {
                        recordId: msg.id,
                    })
                    .then((res) => {
                        if (res.code === '200') {
                            // 2. 通过WebSocket通知对方
                            // const websocket = this.getWebsocket();
                            // if (websocket && websocket.readyState === WebSocket.OPEN) {
                            //   const readMsg = {
                            //     type: 'read_ack',
                            //     uid: this.user.id,
                            //     oppo: this.wsForm.wsOppo,
                            //     msgId: msg.id,
                            //     timestamp: Date.now()
                            //   };
                            //   websocket.send(JSON.stringify(readMsg));
                            // }
                        } else {
                            this.$message.error(
                                '标记消息为已读失败：' + res.msg
                            )
                        }
                    })
                    .catch((error) => {
                        this.$message.error('网络错误，标记消息为已读失败')
                    })
            } else {
                console.warn('无法标记消息为已读：消息ID不存在')
            }
        },
        //发送聊天消息
        sendChatMsg() {
            // 确保富文本编辑器有内容
            if (this.editor) {
                this.wsForm.content = this.editor.txt.html()
            }
            // 表单验证
            this.$refs.wsForm.validate((valid) => {
                if (valid) {
                    const connectionInfo = this.checkWebSocketConnection()
                    if (!connectionInfo.connected) {
                        this.$message.error(connectionInfo.description)
                        console.warn('无法发送消息:', connectionInfo.description)
                        
                        // 提供重连选项
                        this.reconnectWebSocket()
                        return
                    }
                    
                    // 获取WebSocket实例
                    const websocket = this.getWebsocket()
                    if (!websocket) {
                        this.$message.error('WebSocket实例获取失败')
                        console.error('getWebsocket()返回null')
                        return
                    }
                    
                    // 处理特殊字符，避免数据库存储错误
                    let processedContent = this.wsForm.content
                    try {
                        // 可以在这里添加更多的处理逻辑
                        processedContent = processedContent.replace(
                            /[\xF0-\xF7][\x80-\xBF]{3}/g,
                            ''
                        ) // 移除表情符号
                        // this.$message.warning("表情符号比较特殊，对方可能收不到表情符号。")
                    } catch (e) {
                        console.error('处理内容时出错:', e)
                    }
                    const msg = {
                        type: this.messageType,
                        content: processedContent,
                        uid: this.user.id,
                        oppo: this.wsForm.wsOppo,
                        from: this.user.name,
                        to: this.userOptions.find(
                            (item) => item.value === this.wsForm.wsOppo
                        ).label,
                        isRead: 2,
                        msgTime: new Date().toLocaleString(),
                    }
                    try {
                        console.log("WsChat发送消息："+msg)
                        websocket.send(JSON.stringify(msg))
                        if (this.msgList.length > 100) this.msgList.shift() //最多保留100条消息
                        // 清空表单
                        this.wsForm.content = ''
                        if (this.editor) {
                            this.editor.txt.clear()
                        }
                        this.scrollToBottom()
                    } catch (error) {
                        console.error('发送消息失败:', error)
                        this.$message.error('发送消息失败，请重试')
                    }
                }
            })
        },
        clearTimer(index) {
            if (this.timers[index]) {
                clearTimeout(this.timers[index])
                this.timers[index] = null
            }
        },
        // 切换高级设置显示状态
        toggleAdvancedSettings() {
            this.showAdvancedSettings = !this.showAdvancedSettings
        },
        // 滚动消息容器到底部
        scrollToBottom() {
            const container = this.$refs.messageContainer
            if (container) {
                container.scrollTop = container.scrollHeight
            }
        },
        //清空聊天消息
        cleanChatMsg() {
            // 检查是否选择了会话人
            if (!this.wsForm.wsOppo || this.wsForm.wsOppo === '') {
                this.$message.warning('请先选择会话人')
                return
            }
            this.$request.delete('/chat/cleanChatRecords', {
                params: {
                    userId: this.user.id,
                    oppoId: this.wsForm.wsOppo,
                },
            }).then((res) => {
                if (res.code === '200') {
                    this.msgList = []
                    this.$message.success('聊天记录已清空')
                } else {
                    this.$message.error('清空失败：' + res.msg)
                }
            }).catch((error) => {
                this.$message.error('网络错误，清空失败')
                console.error('清空聊天记录失败:', error)
            });
        },
        //初始化用户选择框
        initUsersOptions() {
            this.userOptionsLoading = true
            this.$request({
                method: 'GET',
                url: '/user/getSelect',
            }).then((res) => {
                if (res.code === '200') {
                    this.userOptions = res.data
                    this.autoSelectOpponent()
                } else {
                    this.$message.error(res.msg) //错误信息
                    return false
                }
            }).finally(() => {
                this.userOptionsLoading = false
            })
        },
        
        // 自动选择会话人
        autoSelectOpponent() {
            // 从路由参数或props中获取目标ID
            const targetId = this.$route.query.opponentId || this.opponentId
            if (!targetId) return

            // 确保用户选项已加载完成
            if (this.userOptions.length === 0) {
                console.warn('用户选项尚未加载完成，无法自动选择会话人')
                return
            }

            // 查找匹配的会话人
            const opponent = this.userOptions.find(
                (item) => String(item.value) === String(targetId)
            )
            if (opponent) {
                // 使用$nextTick确保DOM更新完成后再设置值
                this.$nextTick(() => {
                    this.wsForm.wsOppo = opponent.value
                    this.fetchChatRecords(this.user.id, opponent.value)
                })
            } else {
                console.warn(`未找到ID为 ${targetId} 的用户`)
                // 可以选择显示警告消息给用户
                this.$message.warning(`未找到ID为 ${targetId} 的会话人`)
            }
        },
        sendInitMsg() {
            const connectionInfo = this.checkWebSocketConnection()
            if (!connectionInfo.connected) {
                console.warn('无法发送初始化消息:', connectionInfo.description)
                return
            }
            
            const msg = {
                type: 'init',
                content: this.user.id + '号用户正在连接……',
                uid: this.user.id,
                oppo: '0',
            }
            
            try {
                const websocket = this.getWebsocket()
                websocket.send(JSON.stringify(msg))
                console.log('初始化消息发送成功')
            } catch (error) {
                console.error('发送初始化消息失败:', error)
                this.$message.error('初始化消息发送失败，请检查网络连接')
            }
        },
        //弹窗打开后，先显示连接消息，测试是否通畅
        init() {
            // 初始化WebSocket和富文本编辑器
            this.$nextTick(() => {
                this.initializeWebSocket()
                this.initializeEditor()
            })
        },

        initializeWebSocket() {
            const connectionInfo = this.checkWebSocketConnection()
            if (!connectionInfo.connected) {
                console.warn('WebSocket初始化失败:', connectionInfo.description)
                return
            }
            
            const websocket = this.getWebsocket()
            if (!websocket) {
                console.error('无法获取WebSocket实例')
                return
            }
            
            // 添加连接状态监听
            websocket.onopen = () => {
                console.log('WebSocket连接已建立')
                this.$message.success('WebSocket连接成功')
                this.sendInitMsg()
            }
            
            websocket.onerror = (error) => {
                console.error('WebSocket连接错误:', error)
                this.$message.error('WebSocket连接错误，请检查网络连接')
            }
            
            websocket.onclose = (event) => {
                console.log('WebSocket连接已关闭', event)
                this.$message.warning('WebSocket连接已断开')
            }
            
            // 如果已经连接，直接发送初始化消息
            if (websocket.readyState === WebSocket.OPEN) {
                console.log('WebSocket已处于连接状态，直接发送初始化消息')
                this.sendInitMsg()
            }
            
            websocket.onmessage = (event) => {
                this.handleWebSocketMessage(event)
            }
        },

        handleWebSocketMessage(event) {
            try {
                const msg = JSON.parse(event.data)
                console.log("WsChat收到消息："+msg)
                switch (msg.type) {
                    case 'init':
                        this.msgList.push({
                            id: msg.id,
                            type: msg.type,
                            content: msg.content,
                            time: new Date().toLocaleString(),
                            isRead: msg.type === 'me' ? 3 : 2
                        })
                        this.scrollToBottom()
                        break
                        
                    case 'chat':
                    case 'system': 
                        // 同时更新会话人选择框，但避免触发watch重新加载聊天记录
                        const userOption = this.userOptions.find(
                            (item) => item.value.toString() === msg.oppo
                        )
                        if (userOption) {
                            const currentMsgList = [...this.msgList]
                            this.wsForm.wsOppo = userOption.value
                            this.msgList = currentMsgList
                        } else {
                            this.$message.warning('根据对方id没有找到对方名称')
                        }
                        this.msgList.push({
                            id: msg.id,
                            type: 'oppo',
                            content: msg.content,
                            time: new Date().toLocaleString(),
                            isRead: 2
                        })
                        this.scrollToBottom()
                        break
                        
                    case 'chatMe':
                        this.msgList.push({
                            id: msg.id,
                            type: 'me',
                            content: msg.content,
                            time: msg.msgTime,
                            isRead: 2
                        })
                        break
                        
                    case 'read_ack':
                        this.handleReadAck(msg)
                        break
                        
                    case 'refresh':
                        this.handleRefresh(msg)
                        break
                        
                    case 'success':
                    case 'warning':
                    case 'info':
                    case 'error':
                        this.$notify({
                            title: '收到通知',
                            message: msg.content,
                            type: msg.type,
                            duration: 3000,
                        })
                        this.load(this.pageNum)
                        break
                        
                    default:
                        this.$message.warning('未知消息类型')
                }
            } catch (error) {
                console.error('处理WebSocket消息失败:', error)
            }
        },

        initializeEditor() {
            // 新建富文本对象,#editor是内容div的id
            this.editor = new E(`#editor`)
            // 代码高亮插件
            this.editor.highlight = hljs

            // 配置工具栏，添加表格按钮
            this.editor.config.toolbar = [
                ['bold', 'italic', 'underline', 'strike'],
                ['link', 'image', 'video'],
                ['table'],
                ['fontSize', 'fontName', 'foreColor', 'backColor'],
                ['indent', 'outdent'],
                ['alignLeft', 'alignCenter', 'alignRight', 'alignJustify'],
                ['list', 'todoList'],
                ['code', 'quote'],
                ['undo', 'redo'],
            ]

            // 图片上传配置
            this.editor.config.uploadImgServer = this.editorFileUpload
            this.editor.config.uploadFileName = 'file'
            this.editor.config.uploadImgHeaders = {
                token: this.user.token,
            }
            this.editor.config.uploadImgParams = {
                type: 'img',
            }

            // 配置上传成功后的自定义插入逻辑
            this.editor.config.uploadImgHooks = {
                customInsert: (insertImg, result, editor) => {
                    console.log(result)
                    if (result.errno === 0 && result.data?.length > 0) {
                        const imgUrl = result.data[0].url.fileUrl?.trim()
                        if (typeof imgUrl === 'string') {
                            insertImg(imgUrl)
                        } else {
                            this.$message.error('图片URL格式不正确')
                        }
                    } else {
                        this.$message.error(
                            '图片上传失败：' + (result.msg || '无有效数据')
                        )
                    }
                },
            }

            // 上传视频配置
            this.editor.config.uploadVideoServer = this.editorFileUpload
            this.editor.config.uploadVideoName = 'file'
            this.editor.config.uploadVideoHeaders = {
                token: this.user.token,
            }
            this.editor.config.uploadVideoParams = {
                type: 'video',
            }
            
            // 正式创建编辑器
            this.editor.create()
        },
        generateCode() {
            // 创建表单引用
            this.$refs.lingjianForm.validate((valid) => {
                if (valid) {
                    // 表单验证通过，调用接口
                    this.$request
                        .post('/utils/autocode/', this.lingjian)
                        .then((res) => {
                            if (res.code === '200') {
                                this.generatedCode = res.data // 假设接口返回的就是编码
                                this.$message.success('编码生成成功')
                            } else {
                                this.$message.error(
                                    res.message || '生成编码失败'
                                )
                            }
                        })
                        .catch((error) => {
                            this.$message.error('请求失败: ' + error.message)
                        })
                } else {
                    this.$message.error('请填写完整的零件属性信息')
                    return false
                }
            })

            // 这里简单模拟生成14位编码，实际应根据业务规则生成
            // const randomCode = Math.floor(Math.random() * 100000000000000).toString().padStart(14, '0');
            // this.generatedCode = randomCode;

            // 实际应用中，这里应该调用后端API生成编码
            // this.$axios.post('/api/generateCode', this.lingjian)
            //   .then(response => {
            //     this.generatedCode = response.data.code;
            //   })
            //   .catch(error => {
            //     this.$message.error('生成编码失败: ' + error.message);
            //   });
        },
        parseAttributes() {
            if (!this.generatedCode) {
                this.$message.warning('请先填写编码再解析属性')
                return
            }
            this.$request
                .post('/utils/parseAttributes/', this.generatedCode)
                .then((res) => {
                    if (res.code === '200') {
                        const { tuhao, name, guige, cailiao, leibie } = res.data
                        this.lingjian = { tuhao, name, guige, cailiao, leibie }
                        this.$message.success('属性解析成功')
                    } else {
                        this.$message.error(res.message || '解析属性失败')
                    }
                })
                .catch((error) => {
                    this.$message.error('请求失败: ' + error.message)
                })
        },
        clearCount() {
            this.$request
                .get('/utils/clearCount')
                .then((res) => {
                    if (res.code === '200') {
                        this.$message.success(
                            res.data || '连接服务并清除缓存成功'
                        )
                    } else {
                        this.$message.error(res.message || '缓存清除失败')
                    }
                })
                .catch((error) => {
                    this.$message.error('请求失败: ' + error.message)
                })
        },
        resetForm() {
            this.lingjian = {
                tuhao: '',
                name: '',
                guige: '',
                cailiao: '',
                leibie: '',
            }
            this.generatedCode = ''
            // this.$message.success('表单已清空');
        },
        
        // WebSocket连接检查工具方法
        checkWebSocketConnection() {
            const websocket = this.getWebsocket()
            if (!websocket) {
                return {
                    connected: false,
                    readyState: null,
                    readyStateText: 'WebSocket实例不存在',
                    description: 'WebSocket实例为null，请检查网络连接或刷新页面'
                }
            }
            
            let readyStateText = ''
            switch (websocket.readyState) {
                case WebSocket.CONNECTING:
                    readyStateText = '连接中'
                    break
                case WebSocket.OPEN:
                    readyStateText = '已连接'
                    break
                case WebSocket.CLOSING:
                    readyStateText = '关闭中'
                    break
                case WebSocket.CLOSED:
                    readyStateText = '已关闭'
                    break
                default:
                    readyStateText = '未知状态'
            }
            
            return {
                connected: websocket.readyState === WebSocket.OPEN,
                readyState: websocket.readyState,
                readyStateText: readyStateText,
                description: websocket.readyState === WebSocket.OPEN 
                    ? 'WebSocket连接正常' 
                    : `WebSocket当前状态：${readyStateText}，请稍后重试`
            }
        },
        
        // WebSocket重连方法
        reconnectWebSocket() {
            const connectionInfo = this.checkWebSocketConnection()
            if (!connectionInfo.connected) {
                this.$message.warning('WebSocket连接异常，正在尝试重新连接...')
                console.warn('WebSocket状态:', connectionInfo.description)
                
                // 提示用户刷新页面
                this.$confirm('WebSocket连接已断开，是否刷新页面重新连接？', '连接提示', {
                    confirmButtonText: '刷新页面',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    location.reload()
                }).catch(() => {
                    console.log('用户取消刷新')
                })
                
                return false
            }
            return true
        },
    },
    // 组件销毁前清理事件监听器
    beforeDestroy() {
        this.removeResizeListener();
        if (this.editor) {
            this.editor.destroy();
            this.editor = null;
        }
    },
}
</script>

<style scoped>
/* 确保容器不会导致大页面滚动条 */
.ws-chat-container {
    box-sizing: border-box;
    overflow: hidden;
}

.box-card {
    margin: 10px;
    max-height: calc(100% - 20px); /* 限制高度为父容器的100% */
    overflow-y: hidden; /* 避免容器本身出现滚动条 */
}

/* 确保表单元素正确布局 */
.el-form {
    display: flex;
    flex-direction: column;
    height: 100%;
}

/* 确保编辑器区域正确布局 */
#editor {
    box-sizing: border-box;
}

/* 确保消息容器样式正确 */
:deep(.message-container) {
    box-sizing: border-box;
}

/* 修复el-select下拉框被editor覆盖的问题 */
.ws-chat-container {
    position: relative;
}

/* 提高el-select下拉框的z-index */
.ws-chat-select-dropdown {
    z-index: 9999 !important;
}

::v-deep .ws-chat-select-dropdown {
    z-index: 9999 !important;
}

::v-deep .el-select-dropdown {
    z-index: 9999 !important;
}

::v-deep .el-popper {
    z-index: 9999 !important;
}

/* 确保编辑器不会覆盖下拉框 */
::v-deep #editor {
    position: relative;
    z-index: 1;
}

::v-deep .w-e-text-container {
    position: relative;
    z-index: 1;
}

::v-deep .w-e-toolbar {
    position: relative;
    z-index: 1;
}
</style>